package com.chazz.servlet;

import com.alibaba.fastjson.JSONArray;
import com.chazz.entity.User;
import com.chazz.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
//；用户修改查看操作

@WebServlet("/user2.do")
public class User2Servlet extends HttpServlet {
    UserServiceImpl usi=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        //用户操作
        String op=req.getParameter("option");
        System.out.println(op);
        if(op.equals("showInfo")){
            try {
                showInfo(req,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else if(op.equals("userUpdate")){
            userUpdateInfo(req,resp);
        }
    }
    //更新用户信息
    private void userUpdateInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userEmail=req.getParameter("email");
        //String userEmail="1308147704@qq.com";
        String userName=req.getParameter("userName");
        String userPhone=req.getParameter("userPhone");
        String sex=req.getParameter("sex");
        int userSex=Integer.parseInt(sex);
        User user=new User();
        user.setEmail(userEmail);
        user.setUsername(userName);
        user.setPhone(userPhone);
        user.setSex(userSex);
        if(usi.updateUserInfo(user)){
            resp.setContentType("text/plain;charset=UTF-8");
            PrintWriter out=resp.getWriter();
            out.write("true");
            out.close();
        }else{
            //修改失败
            resp.setContentType("text/plain;charset=utf-8");
            PrintWriter out=resp.getWriter();
            out.write("false");
            out.close();

        }
    }

    //查看用户信息
    private void showInfo(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String userEmail=req.getParameter("email");
        //String userEmail="1308147704@qq.com";
        User user=usi.findUserByEmail(userEmail);
        resp.setContentType("application/json;charset=UTF-8");
        String userToJson= JSONArray.toJSONString(user);
        PrintWriter out=resp.getWriter();
        out.write(userToJson);
        out.close();
    }
}
